package com.CST.service.impl.zx;

import com.CST.entity.zx.ZxFinancialBasicInfo;
import com.CST.mapper.cst.zx.ZX_FinancialMapper;
import com.CST.mapper.ufdata.AccvouchMapper;
import com.CST.service.zx.IZxFinancialService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ZxFinancialServiceImp implements IZxFinancialService {

    @Autowired
    ZX_FinancialMapper financialMapper;

    @Autowired
    AccvouchMapper accvouchMapper;

//    @Override
//    public void addAllocations(List<ZX_Appropriation> appropriations) {
//        financialMapper.addAllocations(appropriations);
//    }

    @Override
    public List<ZxFinancialBasicInfo> getList() {
        return financialMapper.getList();
    }

    @Override
    public void deleteFinancialProject(String financialCode) {
        financialMapper.deleteFinancialProject(financialCode);
    }

    @Override
    public void collectFinancialData() {
        //从用友中取出目标数据
        List<ZxFinancialBasicInfo> collectDataList = accvouchMapper.collectFinancialData();

        //从数据库取出现在数据
        List<ZxFinancialBasicInfo> fromDBlist =financialMapper.getList();

        //新增列表
        List<ZxFinancialBasicInfo> newDataList =new ArrayList<>();
        List<String> financialCodeList =new ArrayList<>();
        if(fromDBlist!=null && fromDBlist.size()>0)
        {
             financialCodeList =fromDBlist.stream().map(t->t.getFinancialCode()).collect(Collectors.toList());
        }

        //过滤出新增的数据
        if(collectDataList!=null && collectDataList.size()>0)
        {
            List<String> finalFinancialCodeList = financialCodeList;
            newDataList =collectDataList.stream().filter(t->!finalFinancialCodeList.contains(t.getFinancialCode())).collect(Collectors.toList());
        }

        if(newDataList!=null && newDataList.size()>0)
        {
//            financialMapper.insertFinancialData(newDataList);

            int total = newDataList.size();//为防止插入字符超过最大数,分批插入
            int fromIndex = 0;
            List<ZxFinancialBasicInfo> insertList = new ArrayList<>();
            for (int i = 0; i < newDataList.size(); i++) {
                ZxFinancialBasicInfo item = newDataList.get(i);
                fromIndex++;
                insertList.add(item);
                if (fromIndex % 20 == 0 && fromIndex <= total) {
                    financialMapper.insertFinancialData(insertList);
                    insertList = new ArrayList<>();
                }
            }
            if (CollectionUtils.isNotEmpty(insertList)) {
                financialMapper.insertFinancialData(insertList);
            }
        }

    }
}
